package cn.net.isir.controller.manager;

import cn.net.isir.common.ResultObject;
import cn.net.isir.common.TokenManager;
import cn.net.isir.core.InsertRequired;
import cn.net.isir.entity.ShopUser;
import cn.net.isir.entity.User;
import cn.net.isir.entity.UserInfo;
import cn.net.isir.entity.dto.ShopSubUser;
import cn.net.isir.service2.ShopUserService;
import cn.net.isir.service.UserInfoService;
import cn.net.isir.service.UserService;
import cn.net.isir.utils.RequestUtils;
import cn.net.isir.utils.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author liuxubo
 * @filename ShopSubUserController.java
 * @package cn.net.isir.controller.manager
 * @email lxb@isir.net.cn
 * @date 2018/12/04
 * @comment
 * @since 1.8
 */
@RestController
@RequestMapping("/shopSubUser")
public class ShopSubUserController {


    @Resource
    private ShopUserService shopUserService;
    @Resource
    private UserService userService;
    @Resource
    private UserInfoService userInfoService;

    @RequestMapping(value = "/list/{shopId}", method = RequestMethod.GET)
    public ResultObject list(@PathVariable String shopId) {

        ShopUser shopUser = new ShopUser();
        shopUser.setUserId(TokenManager.getTokenId());
        shopUser.setShopId(shopId);
        ShopUser su = shopUserService.selectOne(shopUser);
        if (su.getIsSubAccount() == 1) {
            return new ResultObject(200, "success", new ArrayList<>());
        }
        ShopUser su2 = new ShopUser();
        su2.setShopId(shopId);
        List<ShopUser> shopUserList = shopUserService.selectList(su2);
        Iterator<ShopUser> iterator = shopUserList.iterator();
        while (iterator.hasNext()) {
            ShopUser su3 = iterator.next();
            if (su3.getUserId().equals(TokenManager.getTokenId())) {
                iterator.remove();
            }
        }
        // 组织返回的用户数据
        List<ShopSubUser> shopSubUserList = new ArrayList<>();
        for (ShopUser suItem : shopUserList) {
            ShopSubUser s = new ShopSubUser();
            s.setUserId(suItem.getUserId());
            try {
                s.setUsername(userService.selectByPrimaryKey(suItem.getUserId()).getUsername());
                s.setName(userInfoService.selectByUserId(suItem.getUserId()).getName());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            shopSubUserList.add(s);
        }
        return new ResultObject(200, "success", shopSubUserList);
    }

    /**
     * 添加店铺子用户
     *
     * @param shopSubUser 店铺子用户信息
     * @return 添加结果
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResultObject add(@RequestBody ShopSubUser shopSubUser) {
        ResultObject checkRo = RequestUtils.checkField(shopSubUser, InsertRequired.class);
        if (checkRo.getResult() != 200) {
            return checkRo;
        }
        // 添加用户
        User user = new User();
        user.setUsername(shopSubUser.getUsername());
        user.setPassword(shopSubUser.getPassword());
        user.setUserType("shopSubUser");
        // 添加用户附加信息
        UserInfo userInfo = new UserInfo();
        userInfo.setName(shopSubUser.getName());
        ResultObject ro = TokenManager.register(user, userInfo);
        //如果新增不成功，返回错误信息
        if (ro.getResult() != 100) {
            return ro;
        }
        //添加对应关系
        ShopUser shopUser = new ShopUser();
        shopUser.setUserId(user.getId());
//        shopUser.setBusinessId();
//        shopUser.setShopId();
        shopUser.setIsSubAccount(1);
        shopUser.setCreateUser(TokenManager.getTokenId());
        try {
            shopUserService.insert(shopUser);
        } catch (Exception ex) {
            ex.printStackTrace();
            //如果关系添加异常，删掉已添加的用户
            TokenManager.deleteUser(user.getId());
            return new ResultObject(500, "user add fail", null);
        }

        shopSubUser.setUserId(user.getId());
        return new ResultObject(200, "success", shopSubUser);
    }


    /**
     * 更新用户信息
     *
     * @param shopSubUser 用户信息
     * @return 更新结果
     */
    @RequestMapping(value = "/save", method = RequestMethod.PUT)
    public ResultObject save(@RequestBody ShopSubUser shopSubUser) {
        User user = new User();
        user.setId(shopSubUser.getUserId());
        user.setUsername(shopSubUser.getUsername());
        user.setPassword(shopSubUser.getPassword());
        UserInfo ui = null;
        // 如果有就修改用户附加信息
        if (StringUtils.isNotBlank(shopSubUser.getName())) {
            ui = new UserInfo();
            ui.setName(shopSubUser.getName());
        }

        ResultObject ro = new ResultObject();
        ro.setResult(100);
        //如果没有
        if (StringUtils.isNotBlank(user.getUsername()) ||
                StringUtils.isNotBlank(user.getPassword()) ||
                StringUtils.isNotBlank(shopSubUser.getName())) {
            ro = TokenManager.editUser(user, ui);
        }
        //用户信息是否修改成功
        if (ro.getResult() != 100) {
            return ro;
        }
        return new ResultObject(200, "success", user);
    }

    /**
     * 删除店铺子账户
     *
     * @param userId 店铺子账户id
     * @return 修改结果
     */
    @RequestMapping(value = "/delete/{userId}", method = RequestMethod.DELETE)
    public ResultObject delete(@PathVariable String userId) {
        ResultObject ro = TokenManager.deleteUser(userId);
        if (ro.getResult() != 100) {
            return ro;
        }
        //删除用户店铺关系表
        ShopUser shopUser = new ShopUser();
        shopUser.setUserId(userId);
        shopUser.setIsSubAccount(1);
        shopUser = shopUserService.selectOne(shopUser);
        if (shopUser != null) {
            shopUserService.delete(shopUser.getId());
        }
        return new ResultObject(200, "success", 1);
    }
}
